// 全局变量
let currentPage = 1;
let pageSize = 10;
let totalPages = 0;
let currentDetailId = null;

// 页面加载完成后初始化
$(document).ready(function () {
    let currentPage = 1;
    let pageSize = 10;
    let totalPages = 0;
    let detailData = [];
    let reviewNo = getUrlParameter('reviewNo');

    // 初始化页面
    initPage();

    function initPage() {
        if (reviewNo) {
            $('#reviewNoTitle').text(reviewNo);
            loadDetailData();
        }
        bindEvents();
    }

    function bindEvents() {
        // 刷新按钮
        $('#refreshBtn').click(function () {
            loadDetailData();
        });

        // 保存编辑
        $('#saveDetailBtn').click(function () {
            saveDetail();
        });

        // 分页事件
        $(document).on('click', '.pagination .page-link', function (e) {
            e.preventDefault();
            const page = $(this).data('page');
            if (page && page !== currentPage) {
                currentPage = page;
                loadDetailData();
            }
        });
    }

    function loadDetailData() {
        const pageData = {
            pageIndex: currentPage,
            pageSize: pageSize,
            keyword: reviewNo || ''
        };

        // 使用ABP框架的约定式API端点
        $.ajax({
            url: '/api/app/detail-services/get-detail-page',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(pageData),
            success: function (response) {
                if (response.code === 200) {
                    detailData = response.resultData || [];
                    totalPages = Math.ceil(response.total / pageSize);
                    renderDetailTable();
                    renderPagination();
                } else {
                    showError('加载数据失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                showError('加载数据失败：' + error);
            }
        });
    }

    function renderDetailTable() {
        const tbody = $('#detailTable tbody');
        tbody.empty();

        if (detailData.length === 0) {
            tbody.append('<tr><td colspan="12" class="text-center">暂无数据</td></tr>');
            return;
        }

        detailData.forEach(function (item) {
            const row = `
                <tr>
                    <td>${item.reviewNo || ''}</td>
                    <td>${item.goodscodeNo || ''}</td>
                    <td>${item.goodscodeName || ''}</td>
                    <td>${formatNumber(item.rqty)}</td>
                    <td>${formatNumber(item.ramout)}</td>
                    <td>
                        <input type="number" class="form-control form-control-sm counted-qty" 
                               value="${item.pqty || 0}" 
                               data-id="${item.id}"
                               onchange="updateCountedQty(this)">
                    </td>
                    <td>${item.unit || ''}</td>
                    <td class="${item.dqty > 0 ? 'text-success' : item.dqty < 0 ? 'text-danger' : ''}">
                        ${formatNumber(item.dqty)}
                    </td>
                    <td class="${item.damount > 0 ? 'text-success' : item.damount < 0 ? 'text-danger' : ''}">
                        ${formatNumber(item.damount)}
                    </td>
                    <td>${getDetailStatusText(item.dstatus)}</td>
                    <td>${formatNumber(item.dprice)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editDetail('${item.id}')">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteDetail('${item.id}')">删除</button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    function renderPagination() {
        const pagination = $('#pagination');
        pagination.empty();

        if (totalPages <= 1) return;

        let paginationHtml = '<ul class="pagination">';
        
        // 上一页
        if (currentPage > 1) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a></li>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                paginationHtml += `<li class="page-item active"><span class="page-link">${i}</span></li>`;
            } else {
                paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
            }
        }

        // 下一页
        if (currentPage < totalPages) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a></li>`;
        }

        paginationHtml += '</ul>';
        pagination.html(paginationHtml);
    }

    function saveDetail() {
        const formData = {
            reviewNo: $('#modalReviewNo').val(),
            goodscodeNo: $('#modalGoodscodeNo').val(),
            goodscodeName: $('#modalGoodscodeName').val(),
            rqty: parseFloat($('#modalRqty').val()) || 0,
            ramout: parseFloat($('#modalRamout').val()) || 0,
            pqty: parseFloat($('#modalPqty').val()) || 0,
            unit: $('#modalUnit').val(),
            dqty: parseFloat($('#modalDqty').val()) || 0,
            damount: parseFloat($('#modalDamount').val()) || 0,
            dstatus: parseInt($('#modalDstatus').val()) || 1,
            dprice: parseFloat($('#modalDprice').val()) || 0,
            dremark: $('#modalDremark').val()
        };

        const isEdit = $('#detailModal .modal-title').text().includes('编辑');
        const url = isEdit ? '/api/app/detail-services/update-detail' : '/api/app/detail-services/add-detail';

        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function (response) {
                if (response.code === 200) {
                    showSuccess(isEdit ? '更新成功' : '添加成功');
                    $('#detailModal').modal('hide');
                    loadDetailData();
                } else {
                    showError((isEdit ? '更新' : '添加') + '失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                showError((isEdit ? '更新' : '添加') + '失败：' + error);
            }
        });
    }

    // 工具函数
    function formatNumber(num) {
        if (num === null || num === undefined) return '0.00';
        return parseFloat(num).toFixed(2);
    }

    function getDetailStatusText(status) {
        const statusMap = {
            1: '待盘点',
            2: '已盘点',
            3: '有盈亏',
            4: '无盈亏'
        };
        return statusMap[status] || '未知';
    }

    function getUrlParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    function showSuccess(message) {
        alert('成功：' + message);
    }

    function showError(message) {
        alert('错误：' + message);
    }

    function showWarning(message) {
        alert('警告：' + message);
    }

    function showInfo(message) {
        alert('信息：' + message);
    }
});

// 全局函数，供HTML调用
function updateCountedQty(input) {
    const id = $(input).data('id');
    const countedQty = parseFloat($(input).val()) || 0;
    
    // 这里可以添加实时更新逻辑
    console.log(`更新盘点数量: ID=${id}, 数量=${countedQty}`);
}

function editDetail(id) {
    // 获取明细数据并填充到模态框
    $.ajax({
        url: `/api/app/detail-services/get-detail/${id}`,
        type: 'GET',
        success: function (response) {
            if (response.code === 200) {
                const detail = response.resultData;
                $('#detailModal .modal-title').text('编辑明细');
                $('#modalReviewNo').val(detail.reviewNo);
                $('#modalGoodscodeNo').val(detail.goodscodeNo);
                $('#modalGoodscodeName').val(detail.goodscodeName);
                $('#modalRqty').val(detail.rqty);
                $('#modalRamout').val(detail.ramout);
                $('#modalPqty').val(detail.pqty);
                $('#modalUnit').val(detail.unit);
                $('#modalDqty').val(detail.dqty);
                $('#modalDamount').val(detail.damount);
                $('#modalDstatus').val(detail.dstatus);
                $('#modalDprice').val(detail.dprice);
                $('#modalDremark').val(detail.dremark);
                $('#detailModal').modal('show');
            } else {
                alert('获取明细数据失败：' + response.message);
            }
        },
        error: function (xhr, status, error) {
            alert('获取明细数据失败：' + error);
        }
    });
}

function deleteDetail(id) {
    if (confirm('确定要删除这条明细记录吗？')) {
        $.ajax({
            url: `/api/app/detail-services/delete-detail/${id}`,
            type: 'DELETE',
            success: function (response) {
                if (response.code === 200) {
                    alert('删除成功');
                    location.reload();
                } else {
                    alert('删除失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                alert('删除失败：' + error);
            }
        });
    }
} 